/**
 * 
 */
package tp8.tsh.commands.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import tp8.tsh.cli.CurrentDirectory;
import tp8.tsh.cli.TSHOutput;
import tp8.tsh.commands.intf.Command;
import tp8.tsh.exc.TSHException;
import tp8.tsh.stream.StreamGobbler;

/**
 * @author tpana
 * 
 */
public class Executor implements Command {

	private TSHOutput out;

	/*
	 * (non-Javadoc)
	 * 
	 * @see tp8.tsh.commands.intf.Command#setTSHOutput(tp8.tsh.cli.TSHOutput)
	 */
	@Override
	public void setTSHOutput(TSHOutput tshOutput) {
		this.out = tshOutput;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see tp8.tsh.commands.intf.Command#getName()
	 */
	@Override
	public String getName() {
		return "ls";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see tp8.tsh.commands.intf.Command#getVersion()
	 */
	@Override
	public String getVersion() {
		return "1.0";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see tp8.tsh.commands.intf.Command#getAliasMap()
	 */
	@Override
	public Map<String, String> getAliasMap() {
		Map<String, String> aliasMap = new HashMap<String, String>();
		return aliasMap;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see tp8.tsh.commands.intf.Command#getArgsRegEx()
	 */
	@Override
	public List<String> getArgsRegEx() {
		List<String> argsList = new ArrayList<String>();
		return argsList;
	}

	@Override
	public void execute(String[] args, CurrentDirectory curDir,
			Map<String, String> envVars) throws TSHException {
		args[0] = parseCommand(args[0], curDir);
		
		try {

			ProcessBuilder pb = new ProcessBuilder(args);
//			Map<String, String> env = pb.environment();
			pb.directory(curDir.getDirectory());

			pb.redirectErrorStream(true);

			Process process = pb.start();

			StreamGobbler outputGobbler = new StreamGobbler(
					process.getInputStream(), this.out.getOut(), "OUTPUT");

			// kick them off
			outputGobbler.run();

			// any error???
			int exitVal = process.waitFor();
			this.out.println("ExitValue: " + exitVal);

		} catch (Exception err) {
			this.out.println(err.getMessage());
		}

	}

	private String parseCommand(String cmd, CurrentDirectory curDir) {
		String fullPath;
		// Check if cmd is full path
		if ((!curDir.contains(cmd)) || (cmd.matches("^([a-zA-Z]:)|(/)|(\\\\).*"))) {
			fullPath = cmd;
		} else {
			fullPath = curDir.getPath() + curDir.getSeparator() + cmd;
		}
		return fullPath;
	}

}
